<template>
  <div>
    <px-row>
      <px-col :span="24" class="water_col">
        <div class="waterdom borderRidus">
          <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
            <px-form-item label="时间维度">
              <px-select v-model="queryParams.dimension" placeholder="请选择" clearable style="width: 210px" filterable @change="timechange">
                <px-option v-for="dict in dimensionList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item label="统计表">
              <px-select v-model="queryParams.reportTyp" placeholder="请选择" style="width: 240px" filterable @change="settable">
                <px-option v-for="dict in reportTypList" :key="dict.itemValue" :label="dict.itemValue" :value="dict.itemValue" />
              </px-select> </px-form-item
            ><px-form-item v-if="queryParams.dimension == 'M'" label="月度">
              <px-date-picker
                v-model="queryParams.formData"
                :disabled-date="disabledDate"
                type="monthrange"
                value-format="YYYY-MM"
                format="YYYY-MM"
                placeholder="请选择月份"
              />
            </px-form-item>
            <px-form-item v-if="queryParams.dimension == 'Y'" label="年度">
              <yearPicker :labelWidth="0" labelText="" :disabledYear="2023" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </px-form-item>
            <px-form-item label="厂区">
              <px-select v-model="queryParams.level" :disabled="facDisabled" placeholder="请选择厂区" clearable style="width: 210px" filterable>
                <px-option v-for="dict in liquidList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item label="核算边界">
              <px-select v-model="queryParams.templateId" placeholder="请选择" style="width: 180px" filterable>
                <px-option v-for="dict in templateIdList" :key="dict.id" :label="dict.templateName" :value="dict.id" />
              </px-select>
            </px-form-item>
            <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery()">搜索</px-button>
            <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
          </px-form>
        </div>
      </px-col>
    </px-row>
    <px-row style="height: calc(100vh - 209px); margin-top: 16px" :gutter="16">
      <px-col :span="24" class="water_col">
        <div v-if="queryParams.reportTyp == '碳排放量统计表'" style="position: relative" class="waterdom borderRidus">
          <px-icon class="loadicon" @click="exportToExcel()">
            <Download />
          </px-icon>
          <modelTitle :title="'碳排放量统计表'" />
          <div class="model_chart" style="margin-top: 16px">
            <px-table v-loading="loading" :data="typeList" :summary-method="getSummaries" show-summary show-overflow-tooltip border>
              <px-table-column label="序号" fixed="left" type="index" width="70" />

              <px-table-column :label="dimension == 'M' ? '月度' : '年度'" prop="name">
                <template #default="scope">
                  <span
                    >{{ scope.row.year }}年<span v-if="scope.row.month != null">{{ scope.row.month }}月</span></span
                  >
                </template>
              </px-table-column>

              <px-table-column label="碳排放量(tCO₂e)" prop="carbonEmission">
                <template #default="scope">
                  <span>{{ scope.row.carbonEmission }}</span>
                </template>
              </px-table-column>

              <px-table-column :label="`${dimension == 'M' ? '月度' : '年度'}占比`" prop="ratio">
                <template #default="scope">
                  <span>{{ scope.row.ratio != null ? `${scope.row.ratio}%` : "-" }}</span>
                </template>
              </px-table-column>

              <px-table-column label="环比" prop="monthOnMonthRatio">
                <template #default="scope">
                  <span>{{ scope.row.monthOnMonthRatio != null ? `${scope.row.monthOnMonthRatio}%` : "-" }}</span>
                </template>
              </px-table-column>
              <px-table-column label="同比" prop="yearOnYearRatio">
                <template #default="scope">
                  <span>{{ scope.row.yearOnYearRatio != null ? `${scope.row.yearOnYearRatio}%` : "-" }}</span>
                </template>
              </px-table-column>

              <template #empty>
                <px-empty :image-size="150" />
              </template>
            </px-table>

            <!-- <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              style="margin-bottom: -10px"
              :total="total"
              @pagination="getList"
            /> -->
          </div>
        </div>
        <div v-if="queryParams.reportTyp == '排放类别统计表'" style="position: relative" class="waterdom borderRidus">
          <px-icon class="loadicon" @click="exportToExcel()">
            <Download />
          </px-icon>
          <modelTitle :title="'排放类别统计表'" />
          <div class="model_chart" style="margin-top: 16px">
            <px-table v-loading="loading" :data="typeList2" height="calc(100vh - 339px)" show-overflow-tooltip border>
              <px-table-column fixed="left" :label="dimension == 'M' ? '月度' : '年度'" prop="name">
                <template #default="scope">
                  <span>{{ scope.row.date }}</span>
                </template>
              </px-table-column>
              <px-table-column v-for="(item, index) in typeList2[0]?.value" :key="index" :label="item.emissionCategoryName">
                <px-table-column label="碳排放量(tCO₂e)" prop="carbonEmission">
                  <template #default="scope">
                    <span :class="scope.row.value[index].mark == 'Y' ? 'fontred' : ''">{{
                      scope.row.value[index].carbonEmission != null ? scope.row.value[index].carbonEmission : "-"
                    }}</span>
                  </template>
                </px-table-column>
                <px-table-column label="占比" prop="ratio">
                  <template #default="scope">
                    <span :class="scope.row.value[index].mark == 'Y' ? 'fontred' : ''">{{
                      scope.row.value[index].ratio != null ? `${scope.row.value[index].ratio}%` : "-"
                    }}</span>
                  </template>
                </px-table-column>
              </px-table-column>

              <px-table-column label="总计" prop="ratio">
                <template #default="scope">
                  <span>{{ scope.row.value.reduce((acc, curr) => acc + curr.carbonEmission, 0).toFixed(2) }}</span>
                </template>
              </px-table-column>
              <template #empty>
                <px-empty :image-size="150" />
              </template>
            </px-table>
          </div>
        </div>
        <px-scrollbar v-if="queryParams.reportTyp == '设施活动统计表'" style="position: relative" class="waterdom borderRidus">
          <px-icon class="loadicon" @click="exportToExcel()">
            <Download />
          </px-icon>
          <modelTitle :title="'设施活动统计表'" />
          <div v-for="(items, index) in typeList3" :key="index" class="model_chart" style="margin-top: 16px">
            <p style="margin-bottom: 10px; font-weight: 600; color: #009dd9">{{ items.emissionCategory }}</p>
            <px-scrollbar>
              <div class="tableTop">
                <div class="topList">设施活动</div>
                <div v-for="item in items.date" :key="item.key" class="topList">{{ item }}</div>
              </div>
              <div v-for="(item2, index) in items.list" :key="index" class="tableMain">
                <div class="topList">{{ item2.name }}</div>
                <div v-for="(value, key) in item2.value" :key="key" class="topList">
                  <span :class="value.mark == 'Y' ? 'fontred' : ''">{{ value.number != null ? value.number : "-" }}</span>
                </div>
              </div>
            </px-scrollbar>
          </div>
        </px-scrollbar>
      </px-col>
    </px-row>
  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import { accountingReportgetEmissionDataReport, accountingEmissionDatadownloadEmissionDataReport } from "@/api/doubleCarbonManage/dataReport";
import { accountingTemplatequery } from "@/api/doubleCarbonManage/accountingBoundary";
const loading = ref(true);
const { proxy }: any = getCurrentInstance();
const exportToExcel = () => {
  proxy.download("post", "/energy/accountingEmissionData/downloadEmissionDataReport", queryParams.value, "水质检测-纯水金属阴阳离子.xlsx");
};
let facDisabled = ref(false);
onMounted(() => {
  if (queryParams.value.dimension == "Y") {
    queryParams.value.startDate = `${new Date().getFullYear() - 4}-01-01 00:00:00`;
    queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
    // getList();
  } else {
    if (new Date().getMonth() == 0) {
      queryParams.value.startDate = `${new Date().getFullYear() - 1}-01-01 00:00:00`;
      queryParams.value.endDate = `${new Date().getFullYear() - 1}-12-31 23:59:59`;
      queryParams.value.formData = [`${new Date().getFullYear() - 1}-01`, `${new Date().getFullYear() - 1}-12`];
      // getList();
    } else {
      queryParams.value.startDate = `${new Date().getFullYear()}-01-01 00:00:00`;
      queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
      queryParams.value.formData = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
      // getList();
    }
  }
  accountingTemplatequery({
    orderByColumn: "",
    isAsc: "",
    templateName: "",
    templateStatus: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 999
  }).then((response: any) => {
    templateIdList.value = response.data;
    queryParams.value.templateId = response.data[0]?.id;
    if (localStorage.getItem("facList")) {
      let faclist = JSON.parse(localStorage.getItem("facList"));
      if (faclist.length == 1) {
        facDisabled.value = true;
        queryParams.value.level = faclist[0].name;
        getList();
      } else if (faclist.length == 2) {
        facDisabled.value = false;
        queryParams.value.level = null;
        getList();
      }
    }
  });
});
const timechange = val => {
  if (val == "Y") {
    queryParams.value.startDate = `${dateValue.value.startYear}-01-01 00:00:00`;
    queryParams.value.endDate = `${dateValue.value.endYear}-12-31 23:59:59`;
  } else {
    const res = getMonthRange(queryParams.value.formData);
    queryParams.value.startDate = res[0];
    queryParams.value.endDate = res[1];
  }
};
function formatDate(date) {
  const pad = num => num.toString().padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}

function getMonthRange(months) {
  const [startMonth, endMonth] = months;

  // 解析起始月份（第一个月的第一天 00:00:00）
  const [startYear, startMonthNum] = startMonth.split("-").map(Number);
  const startDate = new Date(startYear, startMonthNum - 1, 1, 0, 0, 0);

  // 解析结束月份（最后一天 23:59:59）
  const [endYear, endMonthNum] = endMonth.split("-").map(Number);
  const endDate = new Date(endYear, endMonthNum, 0, 23, 59, 59); // 下个月的第 0 天 = 这个月的最后一天

  return [formatDate(startDate), formatDate(endDate)];
}

const settable = () => {
  getList();
};
const disabledDate = time => {
  console.log(time);
  const year = 2023;
  const month = 1;
  const firsmonth = new Date(year, month - 1, 1);
  return time.getTime() < firsmonth.getTime();
};
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;

  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "总计";
      return;
    }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => Number.isNaN(value))) {
      if (index == columns.length - 1 || index == columns.length - 2 || index == columns.length - 3) {
        sums[index] = `/`;
      } else {
        sums[index] = `${values
          .reduce((prev, curr) => {
            const value = Number(curr);
            if (!Number.isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0)
          .toFixed(2)}`;
      }
    } else {
      sums[index] = "";
    }
  });

  return sums;
};
const data = reactive({
  dimensionList: [
    {
      itemName: "月度",
      itemValue: "M"
    },
    {
      itemName: "年度",
      itemValue: "Y"
    }
  ],
  queryParams: {
    reportTyp: "碳排放量统计表",
    dimension: "M",
    startDate: "",
    endDate: "",
    level: null,
    formData: [],
    templateId: ""
  },
  tableData: [
    {
      taskNo: "1",
      taskName: "任务名称",
      responsible: "责任人",
      status: "ONGOING"
    }
  ],
  typeList: [],
  typeList2: [
    {
      time: "2024年1月",
      value: [
        {
          emissionCategoryName: "直接温室气体排放",
          carbonEmission: 2,
          ratio: null
        },
        {
          emissionCategoryName: "输入能源的间接排放",
          carbonEmission: null,
          ratio: null
        },
        {
          emissionCategoryName: "交通运输的间接排放",
          carbonEmission: 0,
          ratio: null
        },
        {
          emissionCategoryName: "组织使用的产品和服务的间接排放",
          carbonEmission: 2,
          ratio: null
        },
        {
          emissionCategoryName: "组织的产品使用过程相关的排放",
          carbonEmission: 3,
          ratio: null
        },
        {
          emissionCategoryName: "其他间接排放源",
          carbonEmission: 4,
          ratio: null
        }
      ]
    },
    {
      time: "2024年2月",
      value: [
        {
          emissionCategoryName: "直接温室气体排放",
          carbonEmission: null,
          ratio: null
        },
        {
          emissionCategoryName: "输入能源的间接排放",
          carbonEmission: null,
          ratio: null
        },
        {
          emissionCategoryName: "交通运输的间接排放",
          carbonEmission: 0,
          ratio: null
        },
        {
          emissionCategoryName: "组织使用的产品和服务的间接排放",
          carbonEmission: null,
          ratio: null
        },
        {
          emissionCategoryName: "组织的产品使用过程相关的排放",
          carbonEmission: null,
          ratio: null
        },
        {
          emissionCategoryName: "其他间接排放源",
          carbonEmission: null,
          ratio: null
        }
      ]
    }
  ],
  typeList3: [],
  dimension: "M",
  reportTyp: "碳排放量统计表",
  templateIdList: []
});
const { queryParams, templateIdList, dimensionList, tableData, typeList2, typeList3, typeList, dimension, reportTyp } = toRefs(data);
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const setTime = () => {
  if (queryParams.value.dimension == "年度") {
    queryParams.value.startDate = `2021-01-01 00:00:00`;
    queryParams.value.endDate = `2024-12-31 23:59:59`;
  }
};
const dateValue = ref<any>({ startYear: new Date().getFullYear() - 1, endYear: new Date().getFullYear() });
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  // queryParams.value.formData = [startYear.toString(), endYear.toString()];
  queryParams.value.startDate = `${startYear}-01-01 00:00:00`;
  queryParams.value.endDate = `${endYear}-12-31 23:59:59`;
};

const liquidList = [
  {
    itemName: "全厂",
    itemValue: null
  },
  {
    itemName: "创新中心一期",
    itemValue: "创新中心一期"
  },
  {
    itemName: "创新中心二期",
    itemValue: "创新中心二期"
  }
];
const timeList = [
  {
    itemValue: "月度"
  },
  {
    itemValue: "年度"
  }
];
const reportTypList = [
  {
    itemValue: "碳排放量统计表"
  },
  {
    itemValue: "排放类别统计表"
  },
  {
    itemValue: "设施活动统计表"
  }
];

const handleQuery = () => {
  console.log(queryParams.value);
  getList();
};
const resetQuery = () => {
  queryParams.value = {
    reportTyp: "碳排放量统计表",
    dimension: "M",
    startDate: "",
    endDate: "",
    level: null,
    formData: []
  };
  if (new Date().getMonth() == 0) {
    queryParams.value.startDate = `${new Date().getFullYear() - 1}-01-01 00:00:00`;
    queryParams.value.endDate = `${new Date().getFullYear() - 1}-12-31 23:59:59`;
    queryParams.value.formData = [`${new Date().getFullYear() - 1}-01`, `${new Date().getFullYear() - 1}-12`];
  } else {
    queryParams.value.startDate = `${new Date().getFullYear()}-01-01 00:00:00`;
    queryParams.value.endDate = `${new Date().getFullYear()}-12-31 23:59:59`;
    queryParams.value.formData = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
  }
  if (localStorage.getItem("facList")) {
    let faclist = JSON.parse(localStorage.getItem("facList"));
    if (faclist.length == 1) {
      facDisabled.value = true;
      queryParams.value.level = faclist[0].name;
      getList();
    } else if (faclist.length == 2) {
      facDisabled.value = false;
      queryParams.value.level = null;
      getList();
    }
  }
};
function getList() {
  loading.value = false;
  if (queryParams.value.dimension == "M") {
    if (queryParams.value.formData != null) {
      const res = getMonthRange(queryParams.value.formData);
      queryParams.value.startDate = res[0];
      queryParams.value.endDate = res[1];
    } else {
      queryParams.value.startDate = "";
      queryParams.value.endDate = "";
    }
  }
  const params = {
    reportTyp: queryParams.value.reportTyp,
    dimension: queryParams.value.dimension,
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    level: queryParams.value.level,
    templateId: queryParams.value.templateId
  };

  accountingReportgetEmissionDataReport(params).then((response: any) => {
    loading.value = false;
    // dimension.value = response.dimension;
    // reportTyp.value = response.reportTyp;
    if (response.data != null) {
      typeList.value = response.data;
    } else {
      typeList.value = [];
    }

    if (response.facilityMap != null) {
      typeList3.value = response.facilityMap;
    } else {
      typeList3.value = [];
    }

    if (response.categoryMap != null) {
      typeList2.value = response.categoryMap;
    } else {
      typeList2.value = [];
    }
    dimension.value = response.dimension;
    console.log(dimension.value);
  });
}
</script>

<style scoped lang="scss">
.water_col {
  height: 100%;
}

.waterdom {
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.first_width {
  width: calc(100% - 16px);
}

.model_chart {
  position: relative;
  width: 100%;
  height: calc(100% - 40px);
  margin-top: 10px;

  .co2img {
    position: absolute;
    top: 32px;
    left: 22px;
    width: 32px;
    height: 32px;
  }

  .titlep {
    position: absolute;
    top: 29px;
    left: 70px;
    font-size: 16px;
    font-weight: 400;
    color: #000;
  }

  .titlevalue {
    position: absolute;
    top: 55px;
    left: 70px;

    .titlevalue1 {
      float: left;
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      color: #3b82f6;
    }

    .titlevalue1span {
      font-size: 16px;
      font-weight: 400;
      line-height: 22px;
      color: #4f4f4f;
    }

    .titlevalue2 {
      float: left;
      margin-top: 5px;
      margin-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #f87171;
    }
  }

  .co2mian {
    position: absolute;
    top: 112px;
    left: 0;
    width: 100%;
    height: 92px;
  }

  .co2mianleft {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianleftp {
      width: calc(100% - 21px);
      height: 22px;
      padding-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
      border-right: 1px solid #cbcdd8;
    }
  }

  .co2mianright {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianrightp {
      width: calc(100% - 45px);
      height: 22px;
      padding-left: 45px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }
  }

  .co2mianleftp2 {
    margin-left: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;

    .co2mianleftp2span {
      font-size: 14px;
      font-weight: 400;
      color: #4f4f4f;
    }
  }

  .co2mianleftp3 {
    float: left;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #000;

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #34d399;
    }
  }
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 26px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 16px;
}

.percentage-value2 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}

.percentage-label2 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.percentage-value3 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  color: #f00;
}

.percentage-label3 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #f00;
}

.jindu1 {
  margin: 24px 0 0 17px;
}

.jindu2 {
  margin: 38px calc((100% - 103px) / 2);
}

.jindu1p {
  width: calc(100% - 24px);
  margin-top: 0;
  font-size: 16px;
  text-align: center;
}

.jindu2p {
  width: 100%;
  margin-top: -40px;
  font-size: 14px;
  text-align: center;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.tableTop {
  display: flex;
  // border-right: 1px solid #dfdfdf;

  .topList {
    flex: 1;
    min-width: 125px;
    padding: 6px;
    font-size: 13px;
    font-weight: bold;
    line-height: 23px;
    color: #000;
    background-color: #e7eefb !important;
    border: 1px solid #dfdfdf;
    border-right: none;

    &:nth-last-child(1) {
      border-right: 1px solid #dfdfdf;
    }
  }
}

.tableMain {
  display: flex;
  // border-right: 1px solid #dfdfdf;

  .topList {
    flex: 1;
    min-width: 125px;
    padding: 6px;
    font-size: 13px;
    line-height: 23px;
    color: #000;
    border: 1px solid #dfdfdf;
    border-top: none;
    border-right: none;

    &:nth-last-child(1) {
      border-right: 1px solid #dfdfdf;
    }
  }
}

.fontred {
  color: red;
}

.loadicon {
  position: absolute;
  top: 25px;
  right: 25px;
  cursor: pointer;
}
</style>
